/**   
 * Copyright © 2016 上海飞岩信息科技有限公司. All rights reserved.
 * 
 * @Title: HttpUtils.java 
 * @Prject: pigtreasurepay
 * @Package: com.irefly.pay.test 
 * @Description: TODO
 * @author: caishuangxi   
 * @date: 2016年3月30日 下午4:58:35 
 * @version: V1.0   
 */
package cn.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
 * @ClassName: HttpUtils
 * @Description: TODO
 * @author: caishuangxi
 * @date: 2016年3月30日 下午4:58:35
 */
public class HttpUtils {
	// 超时设置,30秒
	private static final int TIME_OUT = 10 * 60 * 1000;
	// 页面已经永久移到另外一个新地址
	private static final int HTTP_TEST_ACCESS_REDIRECT = 301;
	// 连接超时异常
	private static final int HTTP_CONNECTTIMEOUTEXCEPTION = 100;
	// 请求超时异常
	private static final int HTTP_INTERRUPTEDIOEXCEPTION = 101;
	// 系统错误
	private static final int HTTP_SYSTEMIOEXCEPTION = 102;

	public static enum HttpMethod {
		GET, POST
	}

	private static Log log = LogFactory.getLog(HttpUtils.class);

	public static String doPost(String url, JSONObject json) throws Exception {
		// POST的URL
		HttpPost httppost = new HttpPost(url);
		// 建立HttpPost对象
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 建立一个NameValuePair数组，用于存储欲传送的参数
		params.add(new BasicNameValuePair("requestData", json.toString()));
		// 添加参数
		httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
		// 设置编码
		HttpResponse response = new DefaultHttpClient().execute(httppost);
		// 发送Post,并返回一个HttpResponse对象
		String result = "";
		if (response.getStatusLine().getStatusCode() == 200) {// 如果状态码为200,就是正常返回
			result = EntityUtils.toString(response.getEntity());
			// 得到返回的字符串
			System.out.println(result);
		}
		return result;
	}
	public static String syncConnectUploadFile(final String url, Map<String, File> fileParas, final HttpMethod method) {
		BufferedReader reader = null;
		String responseResult = "";
		try {
			HttpParams httpParams = new BasicHttpParams();
			// 默认不让重定向,这样就能拿到Location头了
			httpParams.setParameter("http.protocol.handle-redirects", false);
			// // 设置 user agent
			// String userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X
			// 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko)
			// Chrome/32.0.1700.55 Safari/537.36";
			// HttpProtocolParams.setUserAgent(httpParams, userAgent);
			// 设置连接超时时间和数据读取超时时间
			HttpConnectionParams.setConnectionTimeout(httpParams, TIME_OUT);
			HttpConnectionParams.setSoTimeout(httpParams, TIME_OUT);
			// 新建HttpClient对象
			HttpClient httpClient = new DefaultHttpClient(httpParams);
			// HttpUriRequest request = getRequest(url, params, method);
			HttpPost httppost = new HttpPost(url);
			// 添加 post的String 和File数据
			MultipartEntity mEntity = new MultipartEntity();
			// 添加文件
			if (fileParas != null && !fileParas.isEmpty()) {
				for (Map.Entry<String, File> item : fileParas.entrySet()) {
					if (item.getValue().exists()) {
						log.error("upload File is exists and filepath is-->" + item.getKey() + "  "
								+ item.getValue().getPath());
						mEntity.addPart(item.getKey(), new FileBody(item.getValue()));
					} else {
						log.error("upload File is NOT exists!");
					}
				}
			}
			httppost.setEntity(mEntity);
			HttpResponse response = httpClient.execute(httppost);
			int statusCode = response.getStatusLine().getStatusCode();
			log.error("statusCode=" + statusCode);
			if (statusCode == HttpStatus.SC_OK) {
				reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
				StringBuilder sb = new StringBuilder();
				for (String s = reader.readLine(); s != null; s = reader.readLine()) {
					sb.append(s);
				}
				responseResult = sb.toString();
			} else if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
				Header locationHeader = response.getFirstHeader("Location");
				if (locationHeader != null) {
					String location = locationHeader.getValue();
					// LogUtil.e("http", "location="+location);
					responseResult = "{\"code\":" + HTTP_TEST_ACCESS_REDIRECT + ",\"message\":\"" + location + "\"}";
				}
			} else {
				// callback.httpRequest("#" +
				// response.getStatusLine().getStatusCode());
			}
		}// 连接超时异常
		catch (ConnectTimeoutException e) {
			responseResult = "{\"code\":" + HTTP_CONNECTTIMEOUTEXCEPTION + ",\"message\":\"连接超时异常\"}";
			log.error(e.getMessage());
			// httpCallback.httpHandler(resultString);
		}// 请求超时异常
		catch (InterruptedIOException e) {
			responseResult = "{\"code\":" + HTTP_INTERRUPTEDIOEXCEPTION + ",\"message\":\"请求超时异常\"}";
			log.error(e.getMessage());
			// httpCallback.httpHandler(resultString);
		} catch (Exception e) {
			responseResult = "{\"code\":" + HTTP_SYSTEMIOEXCEPTION + ",\"message\":\"操作失败系统遇错\"}";
			e.printStackTrace();
			log.error(e.getMessage());
			// httpCallback.httpHandler(null);
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				// ignore me
			}
		}
		return responseResult;
	}
}
